package com.atguigu.tingshu.payment.api;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;


@Tag(name = "微信支付接口")
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/payment/wxPay")
public class WxPayApiController {

    private WxPayService wxPayService;

    /**
     * 微信支付的通知地址（被动知晓支付结果）
     *
     * @param request 请求
     * @return 地址
     */
    @SneakyThrows
    @RequestMapping(value = "/wxNotifyAddress")
    public String wxNotifyAddress(HttpServletRequest request, String orderNo) {
//        //获取微信通知的数据流
//        ServletInputStream is = request.getInputStream();
//        //声明输出流
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        //声明缓冲区
//        byte[] buffer = new byte[1024];
//        //数据长度
//        int len = 0;
//        //循环读取数据
//        while ((len=is.read(buffer)) != -1){
//            //写
//            os.write(buffer, 0, len);
//        }
//        //获取数据
//        byte[] bytes = os.toByteArray();
//        //转换为字符串
//        String xmlString = new String(bytes);
//        //转换为map数据
//        Map<String, String> result = WXPayUtil.xmlToMap(xmlString);
//        System.out.println(JSONObject.toJSONString(result));
//        //关闭流
//        is.close();
//        os.flush();
//        os.close();

        String resultString = "{\"transaction_id\":\"4200002212202405135980413151\",\"nonce_str\":\"2d28cbc9efcc47bca0cc8028cb994f4a\",\"bank_type\":\"OTHERS\",\"openid\":\"oHwsHuBBoSq3H7CMjvWlIDYSn8Fg\",\"sign\":\"B535FEE360EA03219937ECBC4CAB2B31\",\"fee_type\":\"CNY\",\"mch_id\":\"1558950191\",\"cash_fee\":\"1\",\"out_trade_no\":\"VipOrderNo1789840164026191870\",\"appid\":\"wx74862e0dfcf69954\",\"total_fee\":\"1\",\"trade_type\":\"NATIVE\",\"result_code\":\"SUCCESS\",\"time_end\":\"20240513152428\",\"is_subscribe\":\"N\",\"return_code\":\"SUCCESS\"}";
        Map<String, String> result = JSONObject.parseObject(resultString, Map.class);
        result.put("out_trade_no", orderNo);

        // 修改本地流水记录
        CompletableFuture.runAsync(() -> {
            wxPayService.updatePaymentInfo(result);
        });

        // 返回结果初始化
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("return_code", "SUCCESS");
        returnMap.put("return_msg", "OK");
        return WXPayUtil.mapToXml(returnMap);
    }
}
